package cn.net.cfss.fgbp.provider.manage.utils;

import cn.net.cfss.fgbp.base.util.StringUtils;
import cn.net.cfss.fgbp.spi.manage.constant.DeleteFlagEnum;
import cn.net.cfss.fgbp.spi.manage.dto.BaseDto;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author wutao
 * @version 1.0
 * @date 2021/3/17 11:26
 */
@Service
public class CommUtil {

    public void setOperatorInfo(BaseDto baseDto, HttpServletRequest request) {
        DeleteFlagEnum deleteFlag = baseDto.getDeleteFlag();
        if (deleteFlag == null) {
            baseDto.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        }
        if (baseDto.getCreateBy() == null) {
            baseDto.setCreateBy(getUserId(request));
        }
        if (baseDto.getUpdateBy() == null) {
            baseDto.setUpdateBy(getUserId(request));
        }
        if (baseDto.getCreateTime() == null) {
            baseDto.setCreateTime(new Date());
        }
        if (baseDto.getUpdateTime() == null) {
            baseDto.setUpdateTime(new Date());
        }
    }

    public void setOperatorInfoForUpdate(BaseDto baseDto, HttpServletRequest request) {

        if (baseDto.getUpdateBy() == null) {
            baseDto.setUpdateBy(getUserId(request));
        }
        if (baseDto.getUpdateTime() == null) {
            baseDto.setUpdateTime(new Date());
        }
    }


    private Long getUserId(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String userId = request.getHeader("Authorization-UserId");
        return StringUtils.isEmpty(userId) ? null : Long.valueOf(userId);
    }
}
